import type { RouterConfig } from 'nuxt/schema';

// 简单的设备类型检测函数
const getDeviceType = () => {
  if (typeof window !== 'undefined') {
    const userAgent = window.navigator.userAgent.toLowerCase();
    const isMobile = /mobile|android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
    return isMobile ? 'mobile' : 'pc';
  }
  return 'pc'; // 默认返回pc类型
};

// 导出路由配置项
const customRouterConfig: RouterConfig = {
  routes: (_routes) => {
    // 当前设备的类型
    const targetType = getDeviceType();
    // 不是当前设备类型的另一个类型
    const notTargetType = targetType === 'mobile' ? 'pc' : 'mobile';
    
    // 找到匹配当前设备的所有页面路由
    let targetRoutes = _routes.filter((item) =>
      (item.name as string)?.startsWith(targetType),
    );
    targetRoutes = targetRoutes.map((item) => {
      // 将路由前缀删除
      item.path = item.path.replace(`/${targetType}`, '') === ''
        ? '/' : item.path.replace(`/${targetType}`, '');
      
      // 重定向/到对应的页面
      if (item.path === '/' && item.name === 'pc') {
        item.redirect = '/home';
      }
      if (item.path === '/' && item.name === 'mobile') {
        item.redirect = '/mobileHome';
      }
      
      return item;
    });
    
    // 找到不匹配当前设备的所有页面路由
    let notTargetRoutes = _routes.filter((item) =>
      (item.name as string)?.startsWith(notTargetType),
    );
    notTargetRoutes = notTargetRoutes.map((item) => {
      // 将路由前缀添加上
      if (!item.path.startsWith(`/${notTargetType}`))
        item.path = `/${notTargetType}${item.path}`;
      return item;
    });
    
    const customRoutes = [...targetRoutes, ...notTargetRoutes];
    
    // 添加404页面路由
    customRoutes.push({
      path: '/:path(.*)*',
      name: '404',
      component: () => import('~/pages/404.vue'),
    });
    
    return customRoutes;
  },
};

export default customRouterConfig;
